# -*- coding: utf-8 -*-

import cgi
import sys, os
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import facebook
from facebook import FacebookError

g_ADDRESS='118.169.7.88'
FACEBOOK_API_KEY ='a8dfbf5416044ed379eaf8a4bb424fdf'
FACEBOOK_SECRET_KEY ='e950aa7805c18e5fa6223367810a5e3d'

_DEBUG = True
    
class Utility(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('Utility.js',0))

class FBjqRY(webapp.RequestHandler):
    def get(self):
        self.response.out.write(template.render('FBjqRY.min.js',0))

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('work')
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        friend = fb.friends.get()
        uids = fb.users.getInfo(friend,['uid'])
        ans=fb.admin.getAllocation('notifications_per_day')
        self.response.out.write(ans)
        self.response.out.write(template.render('noti.html',{'uids':uids,'address':g_ADDRESS}))

class notification(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        friend_uid = self.request.get('uid')

        try:
            #fb.notifications.send([friend_uid],u'<fb:name uid="1713094070" firstnameonly="true" />感謝<fb:name uid="'+friend_uid+u'" />幫我<a href="http://www.google.com.tw" >投票</a>','user_to_user')
            #fb.notifications.send([friend_uid],u'<fb:name uid="'+friend_uid+'" firstnameonly="true" />testing~','user_to_user')
            #fb.notifications.send(['1713094070'],u'<fb:name uid="'+friend_uid+'" firstnameonly="true" />testing~','user_to_user')
            
            self.response.out.write('notification %s' % friend_uid)
        except:
            self.response.out.write('error %s' % friend_uid)            
 

def main():
    application = webapp.WSGIApplication([
        ('/',MainPage),
        ('/Utility.js', Utility),
        ('/FBjqRY.min.js', FBjqRY),
        ('/notification',notification)
        ],debug=_DEBUG)
    wsgiref.handlers.CGIHandler().run(application)
    
if __name__ == "__main__":
    main()

       
